import { PlusOutlined } from '@ant-design/icons';
import { Button, message, Popconfirm, Input, Select } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import EditModalForm from './components/EditModalForm.jsx';
import _ from 'lodash';
import request from '@/utils/request';
import apiPath from '@/utils/apiPath.js';
import { filterDateParse } from '@/utils/utils.js';
import { widgetsControl } from '@/utils/authority.js';

const TableList = () => {
  const [authOptions, setAuthOptions] = useState([]);
  const actionRef = useRef();
  const editModalFormRef = useRef();

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      valueType: 'text',
      search: false
    },
    {
      title: '权限名称',
      dataIndex: 'name',
      valueType: 'text',
      search: true,
      renderFormItem: (item, { type, defaultRender, ...rest }, form) => {
        return (
          <Input placeholder="请输入关键字"/> 
        );
      },
    },
    {
      title: 'ACTION_KEY',
      dataIndex: 'action_key',
      valueType: 'text',
      search: false
    },
    {
      title: '类型',
      dataIndex: 'type',
      valueType: 'text',
      search: false,
      valueEnum: {
        0: { text: 'ROOT' },
        1: { text: '菜单组' },
        2: { text: '菜单' },
        3: { text: '操作点' },
      },
    },
    {
      title: '父节点',
      dataIndex: 'pid',
      valueType: 'text',
      search: false,
      renderText: (val) => {
        let lastIndex = _.findLastIndex(authOptions, v => v.id === val);
        return lastIndex !== -1 ?authOptions[lastIndex].name : val;
      },
    },
    {
      title: '新建时间',
      dataIndex: 'created_time',
      renderText: val => filterDateParse(val),
      valueType: 'text',
      search: false
    },
    {
      title: '修改时间',
      dataIndex: 'updated_time',
      renderText: val => filterDateParse(val),
      valueType: 'text',
      search: false
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a 
          key="edit"
          onClick={() => {
            initModal(record);
          }}
        >
          修改
        </a>,
        <Popconfirm
          key="delete"
          title="是否删除该数据？"
          onConfirm={() => {
            handleRemove(record);
          }}
          okText="删除"
          cancelText="取消"
        >
          <a type="link" style={{color: '#ff4d4f'}}>删除</a>
        </Popconfirm>
      ],
    },
  ];

  useEffect(async () => {
    if (!authOptions.length) {
      const res = await request(apiPath.ADMIN_AUTH_HANDLE, {
        method: 'GET',
        params: {
          page: 1,
          per_page: 1000
        },
      })
      setAuthOptions(res.data.list);
    }
  }, [authOptions]);

  /**
   * 删除节点
   *
   * @param id
   */

  const handleRemove = async ({ id }) => {
    if (!id) return true;

    const hide = message.loading('正在删除');
    try {
      await request(`${apiPath.ADMIN_AUTH_HANDLE}/${id}`, {
        method: 'DELETE',
      });
      hide();
      actionRef?.current.reload();
      message.success('删除成功');
      return true;
    } catch (error) {
      hide();
      message.error('删除失败，请重试');
      return false;
    }
  };

  const initModal = (row = {}) => {
    editModalFormRef.current.initModal(row);
  }

  return (
    <PageContainer>
      <ProTable
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 100,
          defaultCollapsed: false
        }}
        pagination={{
          pageSize: 15,
          pageSizeOptions: [15, 30, 60, 100]
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              initModal();
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        request={async (params) => {
          let parseParams = _.omit(params, 'current', 'pageSize');
          parseParams.page = params.current;
          parseParams.per_page = params.pageSize;
          const res = await request(apiPath.ADMIN_AUTH_HANDLE, {
            method: 'GET',
            params: parseParams,
          })
          .catch(() => {
            return false;
          });
          return res ? {
            data: res.data.list,
            success: true,
            total: res.data.page.total
          } : {
            data: [],
            success: true,
            total: 0
          }
        }}
        columns={columns}
      />
      <EditModalForm 
        ref={editModalFormRef}
        onReload={() => {
          actionRef.current.reload();
        }}
      />
    </PageContainer>
  );
};

export default TableList;
